package com.doge.walknovel.business.reader.comments

import android.os.Bundle
import android.view.*
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.doge.wnpro.R
import com.doge.walknovel.api.model.CommentInfo
import com.doge.walknovel.business.novel.NovelRefer
import com.doge.walknovel.business.novel.rating.RatingCommentNovelDialogFragment
import com.doge.walknovel.business.reader.menus.ReaderHelper
import com.doge.walknovel.core.BaseDialogFragment
import com.doge.walknovel.core.base.isRefreshing
import com.doge.wnpro.databinding.DialogFragmentReaderCommentsBinding
import com.doge.walknovel.utils.getColor
import com.doge.walknovel.utils.setOnClickCallback

class ReaderCommentsDialogFragment : BaseDialogFragment() {
    private var innerBinding: DialogFragmentReaderCommentsBinding? = null
    private val binding get() = innerBinding!!
    override val hasShadow = true
    private val light by lazy { ReaderHelper.light }
    private val refer by lazy { arguments?.getString(NovelRefer.EXTRA_REFER)!! }
    private val referId by lazy { arguments?.getInt(NovelRefer.EXTRA_REFER_ID) }
    private val novelId by lazy { arguments?.getInt(EXTRA_NOVEL_ID)!! }
    private val chapterId by lazy { arguments?.getInt(EXTRA_CHAPTER_ID)!! }
    private val viewModel by viewModels<ReaderCommentsViewModel> {
        ReaderCommentsViewModelFactory(novelId, chapterId)
    }
    private val adapter by lazy { ReaderCommentsAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding =
            innerBinding ?: DialogFragmentReaderCommentsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.close.setOnClickCallback {
            dismissAllowingStateLoss()
        }
        binding.input.setOnClickCallback {
            showCreateCommentDialog(null)
        }
        updateInputByLight()
        binding.refreshLayout.setColorSchemeResources(R.color.pull_refresh)
        binding.refreshLayout.setOnRefreshListener {
            viewModel.requestChapterComments()
        }
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)

        viewModel.loading.observe(this) {
            binding.refreshLayout.isRefreshing = it.isRefreshing()
        }
        viewModel.dataList.observe(this) {
            adapter.submitList(it)
        }
        viewModel.requestChapterComments()
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            COMMENTS_REPLY -> {
                showCreateCommentDialog("@${(item as? CommentInfo?)?.nickName} ")
            }
            COMMENTS_COLLECT -> viewModel.requestCollectComments(item as? CommentInfo?)
        }
    }

    private fun updateInputByLight() {
        binding.input.setBackgroundResource(
            if (light) R.drawable.ripple_reader_comment_button
            else R.drawable.ripple_reader_comment_gray_button
        )
        binding.inputImage.setImageResource(if (light) R.mipmap.reader_comments_send else R.mipmap.reader_comments_send_gray)
        binding.input.setTextColor(getColor(if (light) "#333333" else "#d0d0d0"))
    }

    private fun showCreateCommentDialog(value: String?) {
        RatingCommentNovelDialogFragment.newInstance(
            RatingCommentNovelDialogFragment.TYPE_CHAPTER,
            novelId, null, chapterId, value,
            refer, referId
        )
            .show(childFragmentManager)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.close.setOnClickListener(null)
        binding.input.setOnClickListener(null)
        binding.refreshLayout.setOnRefreshListener(null)
        binding.recyclerView.adapter = null
        adapter.setListener(null)
    }

    override fun setWindow(win: Window) {
        win.setWindowAnimations(R.style.Animation_Bottom_Rising)
        win.decorView.setPadding(0, 0, 0, 0)
        val lp = win.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        win.attributes = lp
        win.setGravity(Gravity.BOTTOM)
    }

    companion object {
        private const val EXTRA_NOVEL_ID = "novelId"
        private const val EXTRA_CHAPTER_ID = "chapterId"
        fun newInstance(novelId: Int, chapterId: Int?,
                        refer: String, referId: Int? = null): ReaderCommentsDialogFragment? {
            if (chapterId == null) return null
            return ReaderCommentsDialogFragment().apply {
                arguments = Bundle().apply {
                    putInt(EXTRA_NOVEL_ID, novelId)
                    putInt(EXTRA_CHAPTER_ID, chapterId)
                    putString(NovelRefer.EXTRA_REFER, refer)
                    referId?.let { putInt(NovelRefer.EXTRA_REFER_ID, referId) }
                }
            }
        }
    }
}